package part2;

/**
 * @Author: shaochong
 * @Date: 2021/8/15
 * @Description:
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 *
 * 进阶：你能尝试使用一趟扫描实现吗？
 */


public class Solution19 {
    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        // 定义一个首节点,方便处理链表删除
        ListNode first = new ListNode(0, head);
        ListNode preStart = first;
        ListNode start = head;
        ListNode end = head;

        int i = 1;
        while (end.next != null) {
            // 快速遍历,使end-start拉开长度为n
            if (i < n) {
                i++;
                end = end.next;
            } else {
                // 然后将start和end依次递增,知道end.next=null
                // preStart指针的用处是为了删除节点
                end = end.next;
                preStart = start;
                start = start.next;
            }
        }
        // 删除start节点,start所处的位置即为倒数第n个节点
        preStart.next = start.next;
        return first.next;
    }
    public static void main(String[] args) {
        ListNode n1 = new ListNode(1, null);
        ListNode n2 = new ListNode(2, null);
        n1.next = n2;

        ListNode ans = removeNthFromEnd(n1, 1);
        System.out.println(ans.val);
    }
}
